const Events = require('events');
let ws = null;
let hTimeObj = null;

module.exports = {
    isActiveClose: false,
    host: '',
    port: 0,
    hTimeNum: 0,
    _id: '',
    token: '',
    nextMessageCount: 0,
    tempMessage: [], //ws收到的临时消息
    isStopEvents: false,
    eventEmiter: new Events(),
    _loginSuccess() {
        console.log('HideLoadding')
    },
    _loginError() {
        console.log('HideLoadding')
        this.close();
        global.EJMgr.showToast(data.message)
        // UI.ToolTip({ message: data.message });
    },
    stopEvents() {
        this.isStopEvents = true;
    },
    startEvents() {
        for (let i = 0; i < this.tempMessage.length; i++) {
            this.eventEmiter.emit(this.tempMessage[i].e, this.tempMessage[i]);
        }
        this.isStopEvents = false;
    },
    setOptions(option = {}) {
        option.token && (this.token = option.token);
        option.id && (this.id = option.id);
    },
    getOptions() {
        var msg = { token: this.token, id: this.id }
        return msg;
    },
    setHbTimeOut(boo) {
        if (boo) {
            this.calOutH();
            if (!!ws && ws.readyState == 1) { this.setOutH(); }
        } else {
            this.calOutH();
        }
    },
    calOutH() {
        clearInterval(hTimeObj);
        this.hTimeNum = 0;
    },
    setOutH() {
        hTimeObj = setInterval(() => {
            this.hTimeNum++;
            if (this.hTimeNum > 4) {
                global.EJMgr.showToast('网络连接超时')
                console.log('心跳超时');
                this.calOutH();
                ws.close();
            }
        }, 1000);
    },
    connect(host, port) {
        this.calOutH();
        this.host = host;
        this.port = port;
        let urlStr = `ws://${host}:${port}`;
        if (!!ws && ws.readyState == 1) { this.close(); }
        ws = new WebSocket(urlStr);
        cc.log('ws = new WebSocket(' + urlStr + ')');
        ws.onopen = () => {
            this.setOutH();
            this.isActiveClose = false;
            this.nextMessageCount = 0;
            this.tempMessage = [];
            var msg = { e: 'login', id: this.id};
            this.send(msg);
        };
        // 接收服务端数据时触发事件
        ws.onmessage = (evt) => {
            try {
                let data = JSON.parse(evt.data);
                if (data.e == 'h') {
                    this.hTimeNum = 0;
                    return;
                }
                // cc.log('派发事件：', evt.data);
                if (data.e == 'loginSuccess') {
                    this._loginSuccess(data);
                }
                if (data.e == 'loginError') {
                    this._loginError(data);
                }
                if (this.isStopEvents) {
                    this.tempMessage.push(data);
                } else {
                    this.eventEmiter.emit(data.e, data);
                }
                // this.tempMessage.push(data);
                // if(this.nextMessageCount===data.c){
                //     this.tempMessage.sort((a,b) => {
                //         return a.c-b.c;
                //     })
                //     for(let i=0;i<this.tempMessage.length;i++){
                //         eventEmiter.emit(data.e, data);
                //     }
                //     this.nextMessageCount=this.tempMessage[this.tempMessage.length-1].c+1;
                //     this.tempMessage=[];
                // }
            } catch (e) {
                cc.error('无法处理的消息:', evt.data, e);
            }
        };
        // 断开 web socket 连接成功触发事件
        ws.onclose = () => {
            this.eventEmiter.emit('LineOut');
            this.eventEmiter.emit('LineOut2');
            this.eventEmiter.emit('LineOut3');
            console.log('websocket链接中断！', this.isActiveClose);
            if (!this.isActiveClose) {
                console.log('3秒后自动重连！！');
                setTimeout(() => {
                    this.reConnect();
                }, 3000);
            }
        };
    },
    on() {
        this.eventEmiter.on(...arguments);
    },
    off() {
        this.eventEmiter.removeAllListeners(...arguments);
    },
    once() {
        this.eventEmiter.once(...arguments);
    },
    removeListener() {
        this.eventEmiter.removeListener(...arguments);
    },
    close() {
        this.calOutH();
        this.isActiveClose = true;
        try {
            console.log('close断开连接');
            ws.close();
        } catch (e) {

        }
    },
    reConnect() {
        console.log('开始重连ws');
        this.isActiveClose = false;
        this.connect(this.host, this.port, this._id, this.token);
    },
    send(k,v) {
        if(typeof(k) == 'object'){
            this.sendString(JSON.stringify(k));
        } else {
            this.sendString(JSON.stringify({e:k,v:v}));
        }
    },
    sendString(str) {
        if (!!ws && ws.readyState == 1) {
            // cc.log('发送消息', str);
            ws.send(str);
        }
    },
    getWsReadyState() {
        var status = false;
        if (ws && ws.readyState == 1) {
            status = true;
        }
        return status;
    },
}